<template>
  <HeaderComp></HeaderComp>
  <van-cell-group inset>
    <van-field
      v-model="oldpassword"
      required
      label="旧密码"
      placeholder="请输入旧密码"
      type="password"
    />
    <van-field
      v-model="newpassword"
      required
      label="新密码"
      placeholder="请输入新密码"
      :error-message="errorMessage1"
      @blur="judgePassword"
      type="password"
    />
    <van-field
      v-model="confirmPassword"
      required
      label="确认密码"
      placeholder="请再次输入新密码"
      :error-message="errorMessage2"
      @blur="judgeNewPassword"
      type="password"
    />
  </van-cell-group>
  <button @click="submit" :disabled="!flage" id="changePassBtn">确定</button>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { Dialog } from "vant";
import { useRouter } from "vue-router";
import type { Ref } from "vue";
import { msgCode, userRegister, userChangePass } from "@/api/api";
import { Toast ,showSuccessToast, showFailToast} from "vant";
import { useUserInfoStore } from "@/stores/userInfo";

const router = useRouter();
const oldpassword = ref("");
const newpassword = ref("");
const errorMessage1 = ref("");
const errorMessage2 = ref("");
const confirmPassword = ref("");
const store = useUserInfoStore();
console.log(store);

const flage = computed(() => {
  return oldpassword.value && newpassword.value && confirmPassword.value;
});

const judgePassword = () => {
  errorMessage1.value =
    oldpassword.value === newpassword.value ? "两次密码不能相同" : "";
};
const judgeNewPassword = () => {
  errorMessage2.value =
    confirmPassword.value === newpassword.value ? "" : "两次输入的密码不相同";
};

const submit = async () => {
  const params = {
    userid: localStorage.getItem("userId"),
    oldpassword: oldpassword.value,
    newpassword: newpassword.value,
  };
  const res = (await userChangePass(params)) as any;
  if (res.code === "200") {
    Dialog.confirm({
      title: "修改完成",
      message: "修改成功,立即登录?",
    })
      .then(async () => {
        router.push("/login");
      })
      .catch(() => {
        console.log("取消登录");
      });
  } else {
    showFailToast("修改密码失败");
  }
};
</script>

<style lang="scss" scoped>
#changePassBtn {
  background: yellow;
  height: 100px;
  width: 60%;
  margin: 50px auto;
  border-radius: 30px;
  border: none;
  color: black;
  font-size: 16px;
}
</style>
